<template>
  <div>
    <codemirror
      ref="editor"
      v-model="code"
      :options="editorOptions"
      class="sql-editor"
    ></codemirror>
  </div>
</template>

<script>
import Vue from "vue";
import { codemirror } from "vue-codemirror";
import CodeMirror from "codemirror"; // **✅ 必须导入 CodeMirror**

// **导入 CodeMirror 样式和插件**
import "codemirror/lib/codemirror.css";
import "codemirror/theme/dracula.css";
import "codemirror/mode/sql/sql.js";
import "codemirror/addon/hint/show-hint.css";
import "codemirror/addon/hint/show-hint.js";
import "codemirror/addon/hint/sql-hint.js";

export default Vue.extend({
  components: { codemirror },
  data() {
    return {
      code: "SELECT * FROM users;", // 初始代码
      editorOptions: {
        mode: "text/x-mysql",
        theme: "dracula",
        lineNumbers: true,
        smartIndent: true,
        matchBrackets: true,
        extraKeys: {
          "Ctrl-Space": "autocomplete",
        },
        hintOptions: {
          completeSingle: false,
        },
      },
    };
  },
  mounted() {
    this.enableAutoComplete();
  },
  methods: {
    enableAutoComplete() {
      this.$nextTick(() => {
        const editorInstance = this.$refs.editor?.editor; // **✅ Vue 2 正确获取 CodeMirror 实例**
        if (editorInstance) {
          editorInstance.on("inputRead", (cm, event) => {
            if (!cm.state.completionActive && /^[a-zA-Z_]+$/.test(event.text[0])) {
              cm.showHint({ hint: CodeMirror.hint.sql, completeSingle: false });
            }
          });
        }
      });
    },
  },
});
</script>

<style>
.sql-editor {
  height: 400px;
  border: 1px solid #444;
}
</style>
